package com.sk.weichat.ui.me.wallet;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Question;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.util.keyboard.KeyBoardUtils;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class SetIdentifyQuestionActivity extends BaseActivity implements View.OnClickListener {
    ImageView ivClear;
    EditText edtAnswer;
    TextView tvQuestion;
    Button btnNext;
    PopupWindow popupWindow;
    View divider;
    List<Question> questionList = new ArrayList<>();

    BaseQuickAdapter adapter = new BaseQuickAdapter<Question, BaseViewHolder>(R.layout.item_question, questionList) {
        @Override
        protected void convert(final BaseViewHolder holder, final Question item) {
            TextView tvQuestion = holder.getView(R.id.tv_question);
            tvQuestion.setText(item.getProblem());
            if (item.isSelected) {
                Drawable drawableRight = getResources().getDrawable(R.mipmap.icon_checked);
                drawableRight.setBounds(new Rect(0, 0, drawableRight.getIntrinsicWidth(), drawableRight.getIntrinsicHeight()));
                tvQuestion.setCompoundDrawables(null, null, drawableRight, null);
            } else {
                tvQuestion.setCompoundDrawables(null, null, null, null);
            }
        }
    };

    Question question;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_identify_question);
        TextView tvTitle = findViewById(R.id.tv_title_center);
        //
        tvTitle.setText(getString(R.string.set_identify_question_title));
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        divider = findViewById(R.id.divider);
        findViewById(R.id.tv_question).setOnClickListener(this);

        ivClear = findViewById(R.id.iv_clear);
        ivClear.setOnClickListener(this);
        tvQuestion = findViewById(R.id.tv_question);
        edtAnswer = findViewById(R.id.edt_answer);
        btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(this);

        edtAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                    btnNext.setBackgroundResource(R.drawable.shape_corner_26dp_solid_primary);
                    btnNext.setEnabled(true);
                } else {
                    ivClear.setVisibility(View.GONE);
                    btnNext.setBackgroundResource(R.drawable.shape_corner_26_solid_gray_bdc2c8);
                    btnNext.setEnabled(false);
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < questionList.size(); i++) {
                    if (position == i) {
                        question = questionList.get(position);
                        questionList.get(position).isSelected = true;
                    } else {
                        questionList.get(i).isSelected = false;
                    }
                }
                popupWindow.dismiss();
                tvQuestion.setText(questionList.get(position).getProblem());
                adapter.notifyDataSetChanged();
            }
        });
        setupPopuwindow();

        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tv_question:
                //弹出问题列表
                if (questionList.size() > 0) {
                    showPopuWindow();
                } else {
                    getQuestions(coreManager.getSelfStatus().accessToken);
                }
                break;

            case R.id.btn_next:
                //下一步
                if (null == question) {
                    ToastUtil.showToast(this, R.string.please_check_question);
                    return;
                }
                postAnswer(question.getId(), edtAnswer.getText().toString().trim(), coreManager.getSelfStatus().accessToken);
                break;

            case R.id.iv_clear:
                edtAnswer.setText("");
                break;
        }
    }

    private void showPopuWindow() {
        KeyBoardUtils.hideKeyBoard(mContext, divider);
        popupWindow.showAsDropDown(divider,0, -ViewPiexlUtil.dp2px(mContext,50));
        Drawable drawableRight = getResources().getDrawable(R.drawable.icon_arrow_up);
        drawableRight.setBounds(new Rect(0, 0, drawableRight.getIntrinsicWidth(), drawableRight.getIntrinsicHeight()));
        tvQuestion.setCompoundDrawables(null, null, drawableRight, null);
    }


    private void setupPopuwindow() {
        if (popupWindow != null)
            return;
        popupWindow = new PopupWindow(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        View view = LayoutInflater.from(mContext).inflate(R.layout.popu_dropdown_list, null, false);
        RecyclerView recyclerview = view.findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview.setAdapter(adapter);
        view.findViewById(R.id.view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Drawable drawableRight = getResources().getDrawable(R.drawable.icon_arrow);
                drawableRight.setBounds(new Rect(0, 0, drawableRight.getIntrinsicWidth(), drawableRight.getIntrinsicHeight()));
                tvQuestion.setCompoundDrawables(null, null, drawableRight, null);
            }
        });
    }

    private void getQuestions(String access_token) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        HttpUtils.post().url(coreManager.getConfig().IDENTIFY_QUESTIONS)
                .params(params)
                .build()
                .execute(new ListCallback(Question.class) {

                    @Override
                    public void onResponse(ArrayResult result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            questionList.clear();
                            questionList.addAll(result.getData());
                            adapter.notifyDataSetChanged();
                            showPopuWindow();
                        } else {
                            //获取问题列表失败
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }


    private void postAnswer(String problemBaseId, String answer, String access_token) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        params.put("problemBaseId", problemBaseId);
        params.put("answer", answer);
        HttpUtils.post().url(coreManager.getConfig().SET_IDENTIFY_QUESTIONS)
                .params(params)
                .build()
                .execute(new BaseCallback(Void.class) {
                    @Override
                    public void onResponse(ObjectResult result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            EventBus.getDefault().post("set_question");//设置问题成功  发送通知 关闭上个页面
                            //设置问题成功
                            startActivity(new Intent(SetIdentifyQuestionActivity.this, SetPayPwdActivity.class).putExtra("PayPasswordType", AppConstant.SET_PAY_PASSWORD_TYPE_ALIYUN));
                            finish();
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(mContext, e.toString());
                    }
                });
    }


    @Override
    protected void onStop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            showPopuWindow();
        }
        super.onStop();
    }
}
